<?php
/**
 * Created by PhpStorm.
 * User: zhana0
 * Date: 18-3-2
 * Time: 上午10:50
 */


$server = new swoole_websocket_server("0.0.0.0", 1024);
$redis = new Redis;
$redis->connect('127.0.0.1', 6379);

$server->on('open', function (swoole_websocket_server $server, $request) {
    //新连接的客户端返回客户端id
    $server->push($request->fd,json_encode(['type'=>'login','client_id'=>$request->fd]));
});

$server->on('message', function (swoole_websocket_server $server, $frame) use ($redis) {

    $data = json_decode($frame->data,true);

    switch ($data['type']) {

        case 'bind_client'://将客户端id与用户id绑定，存入redis

            if ($fd = $redis->get($data['user_id'])) {
                $redis->del($fd,$data['user_id']);
                $server->push($fd,json_encode(['type'=>'logout']));
            }

            $redis->set($data['user_id'],$data['client_id']);
            $redis->set($data['client_id'],$data['user_id']);

            break;

        case 'send_to_friend'://发送信息给好友

            $fd = $redis->get($data['friend_id']);
            if ($fd) {
                $server->push($fd,json_encode(['type'=>'msg','msg'=>$data['msg'],'from'=>$data['from']]));
            }

            break;

        default:
            break;
    }

});

$server->on('close', function ($ser, $fd) use ($redis) {
    $id = $redis->get($fd);
    $redis->del($id,$fd);
});

$server->start();